<template>
  <div class="search-result">
    <!-- 企业名称搜索区域 -->
    <div class="company-search-container">
      <el-input v-model="searchForm.name" clearable placeholder="请输入企业名称、经营范围等关键字" style="width: 1029px;"
        @keyup.enter.native="handleCompanySearch(1)">
        <template #prefix>
          <el-icon style="color: #383838; margin-right: 5px;">
            <Search />
          </el-icon>
        </template>
        <template #append>
          <!-- 给按钮添加自定义类名 -->
          <el-button type="primary" @click="handleSearch()" class="custom-search-btn">
            查询一下
          </el-button>
        </template>
      </el-input>
    </div>
    <div class="search-form-container">
      <div class="filter-container">
        <div class="filter-header">
          <div class="filter-label" style="width: 120px;border-right: none; ">筛选条件</div>
        </div>
        <div class="filter-item">
          <div class="filter-label">国家</div>
          <div class="filter-content">
            <el-select v-model="searchForm.country" placeholder="选择国家" @change="handleCountryChange">
              <!-- 使用后端返回的顶级地区数据（pcode: "0"） -->
              <el-option v-for="country in countries" :key="country.code" :label="country.name" :value="country.code" />
            </el-select>
          </div>
        </div>
        <div class="filter-item">
          <div class="filter-label">城市区域</div>
          <div class="filter-content" style="display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      gap: 15px 10px;
      min-height: 53px;
      word-break: break-all;
      white-space: normal;
    ">
            <!-- Remove the v-for loop here - we only need one selector -->
            <CityRegionSelector v-model="searchForm.city"
              v-for="(city, index) in getCitiesByCountry(searchForm.country)" :country-code="index"
              :city-code="searchForm.exhibitionIds" :city-options="city" :on-child-data="handleCityChildData" />
          </div>
        </div>
        <div class="filter-item">
          <div class="filter-label">所属行业</div>
          <div class="filter-content">
            <el-cascader :options="industries" :emit-path="false" :show-all-levels="false" :props="props"
              style="min-width: 456px" :check-strictly="true" collapse-tags @change="handleIndustryChange"
              v-model="searchForm.industry" clearable></el-cascader>

          </div>
        </div>
        <div class="filter-item">
          <div class="filter-label">展会时间</div>
          <div class="filter-content">
            <el-checkbox-group v-model="searchForm.year" @change="handleYearChange">
              <el-checkbox v-for="time in exhibitionData" :key="time" :label="time.year">
                {{ time.year }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div class="filter-item" v-if="ExhibitList.length != 0">
          <div class="filter-label">展会名称</div>
          <div class="filter-content">
            <el-checkbox-group v-model="searchForm.exhibitionIds"  @change="handleCompanySearchy">
              <!-- 修正循环变量问题 -->
              <el-checkbox v-for="exhibition in ExhibitList" :key="exhibition.id" :label="exhibition.id"
                :disabled="exhibition.lockFlag == 1" @click="handleExhibitionClick(exhibition)">
                {{ exhibition.exhibitionName }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div class="filter-item">
          <div class="filter-label">成立年限</div>
          <div class="filter-content">
            <el-checkbox-group v-model="searchForm.foundingYears">
              <!-- 修正循环变量问题 -->
              <el-checkbox v-for="years in foundingYears" @change="handleCompanySearch(1)" :key="years.value"
                :label="years.value">
                {{ years.label }}
              </el-checkbox>
            </el-checkbox-group>
            <!-- <el-radio-group v-model="searchForm.foundingYears">
              <el-radio v-for="years in foundingYears" :key="years.value" :label="years.value"
                @click="handleRadioClick(years.value,'foundingYears')">
                {{ years.label }}
              </el-radio>
            </el-radio-group> -->
          </div>
        </div>
        <div class="filter-item">
          <div class="filter-label">组织机构</div>
          <div class="filter-content">
            <el-checkbox-group v-model="searchForm.orgType" @change="handleCompanySearch(1)">
              <!-- 这里需要实际的组织机构数据，暂时用示例数据 -->
              <el-checkbox v-for="(org, index) in isExpanded ? orgList : orgList.slice(0, 10)" :key="index"
                :label="org">
                {{ org }}
              </el-checkbox>
            </el-checkbox-group>
            <div class="expand-btn" v-if="orgList.length > 10" style="text-align: center;"
              @click="toggleOrgListDisplay">
              {{ isExpanded ? '收起' : '查看更多<<' }} </div>
            </div>
          </div>
          <div class="filter-item" style="border-bottom: none;">
            <div class="filter-label">注册资本</div>
            <div class="filter-content">
              <el-checkbox-group v-model="searchForm.registeredCapital">
                <el-checkbox v-for="capital in capitalOptions" @change="handleCompanySearch(1)" :key="capital.value"
                  :label="capital.value">
                  {{ capital.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>

      </div>
      <GlobalModal v-model:visible="showOpenMemberModal" title="开通会员" :element-loading-fullscreen="true"
        :element-loading-lock="true"></GlobalModal>
      <div class="conpay-ifo">
        <!-- 加载图片 -->
        <div v-if="isLoading" style="text-align: center; padding: 40px 0;">
          <img src="@/assets/images/looder.png" alt="加载中" style="width: 156px;
height: 93.53px;margin-top: 86px;">
        </div>
        <CompanyInfo v-for="(companyInfo, index) in companyInfoList" :key="index" :companyInfo="companyInfo"
          @child-action="handleCompanyChildAction" :search-keyword="searchForm.name.trim()" />
        <div class="kong" v-if="companyInfoList.length == 0 && !isLoading">
          <img src="@/assets/images/kong.png" alt="">
          暂无搜索结果，<span @click="showOpenMemberModal = true;">请解锁查看更多客户</span>

        </div>
        <div class="pagination-container" style="margin-top: 20px; text-align: center;">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
            layout="  prev, pager, next, jumper" @current-change="handlePageChange"
            @size-change="handlePageSizeChange" />
        </div>
      </div>

    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, onActivated } from 'vue';
import { useRoute, useRouter } from 'vue-router'; // 导入路由工具
const router = useRouter();
// 引入 options 和 companyInfoList 数据
// import { companyInfoList } from './constants/listData';
import baseService from "@/service/baseService";
// 引入 CompanyInfo 组件
import CompanyInfo from './constants/CompanyInfo.vue';
import CityRegionSelector from './constants/CityRegionSelector.vue';
const route = useRoute();
const displayCount = ref(3);
import { ElMessage } from 'element-plus';
// 模拟数据
// 移除硬编码的国家和城市数据
// const countries = ref([...])
// const cityData = ref({...})

// 声明地区数据（从后端获取）
const options = ref([]);
const isLoading = ref(false); // 添加加载状态变量
const showOpenMemberModal = ref(false);
const cityList = ref([]);//备用组件储存数据用的
const orgList = ref([]);//组织
const ExhibitList = ref([]);//展会
// 分页状态变量
const currentPage = ref(1); // 当前页码
const pageSize = ref(10);   // 每页条数
const total = ref(0);       // 总条数
const props = ref({
  children: 'children',
  label: 'label',
  value: 'label',
  multiple: true,
});
const industries = ref([]);//行业
const companyInfoList = ref([]);//公司列表
const searchForm = reactive({
  name: '',
  city: [],  // 将初始值从字符串改为空数组
  companyName: '',
  industry: [],
  year: [],
  orgType: [],
  country: '',
  exhibitionIds: [],
  foundingYears: [],
  organization: [],
  registeredCapital: []
})
const industry = ref([]);//行业列表

const isExpanded = ref(false); // 控制展开/收起状态
// 定义成立年限选项及对应的月份范围
const foundingYears = ref([
  { label: '3个月内', value: '3months', min: 0, max: 3 },
  { label: '半年内', value: '6months', min: 0, max: 6 },
  { label: '一年内', value: '1year', min: 0, max: 12 },
  { label: '1-3年', value: '1-3years', min: 13, max: 36 },
  { label: '3-5年', value: '3-5years', min: 37, max: 60 },
  { label: '5-10年', value: '5-10years', min: 61, max: 120 },
  { label: '十年以上', value: '10years', min: 121, max: 400 }
]);
const capitalOptions = ref([
  { label: '100万以内', value: '100w以内', min: 0, max: 100 },
  { label: '100-200万', value: '100-200w', min: 100, max: 200 },
  { label: '200-500万', value: '200-500w', min: 200, max: 500 },
  { label: '500-1000万', value: '500-1000w', min: 500, max: 1000 },
  { label: '1000万-5000万', value: '1000-5000w', min: 1000, max: 5000 },
  { label: '5000万以上', value: '5000w以上', min: 5000, max: 100000 }
]);
// 计算属性：获取顶级国家（pcode为"0"的地区）
const countries = computed(() => {
  return options.value.filter(item => item.pcode === "0") || [];
});
// 声明并初始化展会数据
const exhibitionData = ref({
  // 添加默认空对象初始化
  '2025-01-01': [],
  '2025-02-01': []
});
const toggleOrgListDisplay = () => {
  isExpanded.value = !isExpanded.value;
};
// 根据国家code获取城市列表
const getCitiesByCountry = (countryCode: string) => {
  if (countryCode == "") {
    return
  }
  // 找到选中的国家对象
  const selectedCountry = options.value.find(item => item.code === countryCode);
  console.log(selectedCountry)
  // 返回其children作为城市列表
  return selectedCountry?.children || [];
};
const handleSearch = () => {
  if (searchForm.name == '') return ElMessage({
    message: '请输入搜索关键词',
    type: 'warning',
  });
  router.push({
    path: '/search-result',
    query: {
      name: searchForm.name
    }
  })
  // 这里可以添加实际的搜索请求逻辑
};
const handleIndustryChange = (value, selectedOptions) => {
  // Add your industry change handling logic here
  // selectedOptions数组的最后一项即为最后一级数据
  industry.value = value ? value.map(path => path[path.length - 1]) : [];
  handleCompanySearch(1)
  console.log('最后一级数据:', industry.value);
  // You can add further processing here
};
const handleCompanySearchy = (val: any) => {
console.log('val', val)
if(val.length == 0){
      searchForm.city = []
    cityList.value = []
}
  handleCompanySearch(1)

  // 这里可以添加实际的搜索请求逻辑
};
// 城市选择子组件数据接收处理方法
const handleCityChildData = (data: { index: string; list: string[] }) => {
  
  if (data.index == -1) {
    showOpenMemberModal.value = true;
    console.log('点击了锁定的展会项:', data.list);
  } else {
    // 现在findIndex可以正常工作，因为cityList.value是数组
    const existingItemIndex = cityList.value.findIndex(item => item.index === data.index);
    if (existingItemIndex > -1) {
      cityList.value[existingItemIndex].list = data.list;
    } else {
      cityList.value.push({ index: data.index, list: data.list });
    }

    searchForm.city = cityList.value.flatMap(item => item.list);
    console.log('searchForm.city', searchForm.city);
    handleCompanySearch(1);
  }

};
const handlePageSizeChange = (size: number) => {
  pageSize.value = size; // Correctly update ref value in script
  handleCompanySearch(1);
};
// 数据获取方法
const nuwdata = async () => {
  try {
    // 并行获取城市数据和年份数据
    const [cityRes, yearRes] = await Promise.all([
      baseService.get('/noc/basearea/getCompanyBasicInfoCity', {}),
      baseService.get('/noc/companybasicinfo/queryExhibitionYear', {})
    ]);


    if (yearRes.code == 0) {
      exhibitionData.value = yearRes.data || [];  // 存储完整地区数据
      const exhibilisttionIds = exhibitionData.value
        .filter(item => item.lockFlag === 0)  // 筛选lockFlag为0的项
        .map(item => item.year);
      searchForm.year = exhibilisttionIds
    }

    const ExhibitLists = await baseService.post('/noc/companybasicinfo/getExhibitionList', {
      year: searchForm.year.join(',')
    })
    if (ExhibitLists.code == 0) {
      ExhibitList.value = ExhibitLists.data || [];  // 存储完整地区数据
      searchForm.organization = [];
      const targetIds = ExhibitList.value
        .filter(item => item.lockFlag === 0)  // 筛选lockFlag为0的项
        .map(item => item.id);
      searchForm.exhibitionIds = targetIds
      console.log('targetIds=====', targetIds)

    }
    if (cityRes.code == 0) {
      options.value = cityRes.list || [];  // 存储完整地区数据
      searchForm.country = "1"
      //     // getCitiesByCountry('1');
    }
    handleCompanySearch(1)
  } catch (error) {
    console.error('数据获取失败:', error);
  }

  // 再获取组织列表
  baseService.get('/noc/companybasicinfo/getCompanyList', {}).then((res) => {
    if (res.code == 0) {
      orgList.value = res.data || [];  // 存储完整地区数据
      console.log(orgList.value, "orgList.value")
    }
  });
  // 再获取行业列表
  baseService.get('/noc/companybasicinfo/getIndustryTree', {}).then((res) => {
    if (res.code == 0) {
      industries.value = res.data || [];  // 存储完整地区数据
    }
  });

};
// 定义处理子组件事件的方法
const handleCompanyChildAction = (data: any) => {
  console.log('从CompanyInfo接收的数据:', data);
  showOpenMemberModal.value = true;

  // 这里添加SearchResult.vue中的业务逻辑
};
// 处理时间选择
const handleYearChange = (val: string[]) => {

  console.log(val)
  // 再获取展会列表
  baseService.post('/noc/companybasicinfo/getExhibitionList', {
    year: val.join(',')
  }).then((res) => {
    if (res.code == 0) {
      ExhibitList.value = res.data || [];  // 存储完整地区数据
    }
  });
  searchForm.organization = [];
}
const handleCountryChange = () => {
  searchForm.city = []
};
const getMatchedCities = () => {
  const cities = getCitiesByCountry(searchForm.country) || [];
  
  // 递归搜索城市及其子节点
  const findCity = (cityList, value) => {
    for (const city of cityList) {
      if (city.code === value || city.name === value) {
        return city;
      }
      // 处理children节点
      if (city.children && Array.isArray(city.children)) {
        const found = findCity(city.children, value);
        if (found) return found;
      }
    }
    return null;
  };
  
  return searchForm.city.map(cityValue => {
    return findCity(cities, cityValue);
  }).filter(Boolean);
};
// 处理企业名称搜索
const handleCompanySearch = (pageNum: number = 1) => {
  if (searchForm.name == '') return ElMessage({
    message: '请输入搜索关键词',
    type: 'warning',
  });
  if (searchForm.exhibitionIds.length == 0 && searchForm.city.length == 0) {
    companyInfoList.value = []; searchForm.city = []; cityList.value = []

    return ElMessage({
      message: '至少选择一个展会或城市区',
      type: 'warning',
    });
  }
searchForm.city = searchForm.city.filter((item: string) => item !== '');
const matchedCities = getMatchedCities();
const hasInvalidCity = matchedCities.some(city => city.isOwn !== 2);
 console.log('getMatchedCities', matchedCities);

  if (searchForm.exhibitionIds.length == 0 && hasInvalidCity) {


    ElMessage.warning('所选城市包含非自有城市，请重新选择');
    return;
  }

  // 将数组转换为逗号分隔的字符串
  const cityCodeStr = searchForm.city.join(',');
  const orgTypeStr = searchForm.orgType.join(',');
  const industrys = industry.value.join(',')
  const exhibitionIdsStr = searchForm.exhibitionIds.join(',')
  // 根据选中的成立年限计算月份范围
  const selectedYears = foundingYears.value.filter(
    item => searchForm.foundingYears.includes(item.value)
  );
  let list = []
  console.log(selectedYears)

  if (selectedYears.length != 0) {
    selectedYears.map(item => list.push({
      minEstablishedMonths: item.min,
      maxEstablishedMonths: item.max
    }))
  }

  // 根据选中的注册资本计算金额范围
  const selectedCapital = capitalOptions.value.filter(
    item => searchForm.registeredCapital.includes(item.value)
  );
  console.log(selectedCapital, "selectedCapital")
  let listCapital = []
  if (selectedCapital.length != 0) {
    selectedCapital.map(item => listCapital.push({
      minCapital: item.min,
      maxCapital: item.max
    }))
  }
  // const minCapital = selectedCapital?.min || 0;
  // const maxCapital = selectedCapital?.max || 0;
  // 动态构建查询参数（排除空值和0值）
  const params = {
    exhibitionIds: '',
    minEstablishedMonths: '',
    maxEstablishedMonths: '',
    page: pageNum, // 直接使用 pageNum 作为页码
    limit: pageSize.value
  };

  // 添加展会ID参数
  if (exhibitionIdsStr) {
    params.exhibitionIds = exhibitionIdsStr;
  }
  if (industrys) {
    params.industryCategory = industrys;
  }
  // 名称关键词（非空字符串）
  if (searchForm.name.trim()) {
    params.name = searchForm.name.trim();
  }
  // 组织类型（非空字符串）
  if (searchForm.orgType.length != 0) {
    params.orgType = orgTypeStr;
  }
  //成立年限
  /* if (list.length != 0) {
     params.selectedYears = list
   }*/
  // 城市编码（非空字符串）
  if (cityCodeStr) {
    params.city = cityCodeStr;
  }

  //成立年限
  if (foundingYears.length != 0) {
    // 循环遍历selectedYears，取最小min值赋值给minEstablishedMonths， 取max最大值给maxEstablishedMonths
    if (selectedYears.length !== 0) {
      const minEstablishedMonths = Math.min(...selectedYears.map(item => item.min));
      const maxEstablishedMonths = Math.max(...selectedYears.map(item => item.max));

      // 将这些值添加到params中
      params.minEstablishedMonths = minEstablishedMonths;
      params.maxEstablishedMonths = maxEstablishedMonths;
    }
  }

  // 注册资金范围（非0值）
  if (listCapital.length != 0) {
    const minCapital = Math.min(...listCapital.map(item => item.minCapital));
    const maxCapital = Math.max(...listCapital.map(item => item.maxCapital));
    params.minCapital = minCapital;
    params.maxCapital = maxCapital;
  }
  companyInfoList.value = []
  isLoading.value = true; // 开始加载
  // // 成立年限范围（非0值）
  // if (minEstablishedMonths !== 0 || maxEstablishedMonths !== 0) {
  //   params.minEstablishedMonths = minEstablishedMonths;
  //   params.maxEstablishedMonths = maxEstablishedMonths;
  // }

  // 注册资本范围（非0值）
  // if (minCapital !== 0 || maxCapital !== 0) {
  //   params.minCapital = minCapital;
  //   params.maxCapital = maxCapital;
  // }
  // if (listCapital.length != 0) {
  //   params.selectedCapital = listCapital
  // }
  // 转换为查询字符串
  const queryString = Object.entries(params)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');
  baseService.post('/noc/companybasicinfo/list', params, {}).then((res) => {
    if (res.code == 0) {
      isLoading.value = false; // 请求完成隐藏加载
      companyInfoList.value = res.page.list || [];
      total.value = res.page.totalCount || 0; // 接收总条数
      currentPage.value = pageNum;       // 更新当前页码
      // industries.value = res.data || [];  // 存储完整地区数据
    }
  });
  // 这里可以添加实际的企业名称搜索逻辑，如调用 API
  console.log('搜索参数:', {
    name: searchForm.name,
    city: cityCodeStr,
    // 输出计算后的月份范围
    // minEstablishedMonths,
    // maxEstablishedMonths,
  });

};

// 分页页码变化事件
const handlePageChange = (pageNum: number) => {
  handleCompanySearch(pageNum);
};
// 添加展会项点击事件处理
const handleExhibitionClick = (exhibition: any) => {
  // 仅处理lockFlag==1的项（禁用状态的展会）
  if (exhibition.lockFlag === 1) {
    showOpenMemberModal.value = true;
    console.log('点击了锁定的展会项:', exhibition.exhibitionName);
    // 可添加具体业务逻辑（如弹窗提示、跳转等）
    // ElMessage.info(`"${exhibition.exhibitionName}" 需开通会员查看`);
  } else {
    console.log(searchForm.exhibitionIds)
    // handleCompanySearch(1)
  }
};
// 组件挂载时执行初始化操作
onMounted(() => {
  // 可以在这里添加获取买家客户列表数据的逻辑
  const urlName = route.query.name;
  if (urlName && typeof urlName === 'string') {
    searchForm.name = urlName;
  }
  console.log('买家客户列表页面已加载');
});
onActivated(() => {
  const urlName = route.query.name;
  if (urlName && typeof urlName === 'string') {
    searchForm.name = urlName;
    // handleCompanySearch(1);
  }
  nuwdata()
});
</script>

<style scoped lang="less">
.search-result {
  padding: 20px;
}

.kong {
  padding: 28px;
  width: 447px;
  margin: 0 auto;
  font-size: 18px;
  text-align: center;

  span {
    color: rgba(22, 119, 255, 1);
  }
}

.company-search-container {
  display: flex;
  justify-content: center;
  /* 让搜索框和按钮居中 */
  margin-bottom: 20px;
}

.search-form-container {
  border: 1px solid #C7C7C7;
  width: 1525px;
  margin: 0 auto;
  /* 让整个表单容器居中 */
}

.conpay-ifo {
  width: 1525px;
  margin: 0 auto;
}

.filter-container {
  width: 100%;
}

.expand-btn {
  text-align: center;
  font-size: 16px;
  color: rgba(22, 119, 255, 1);
  cursor: pointer
}

::v-deep .el-checkbox.is-disabled {

  /* 禁用状态下的文本颜色 */
  .el-checkbox__label {
    color: #909399;
    float: right;
    line-height: 20px;
    display: block !important;
    /* 调整为较深的灰色，默认是 #c0c4cc */
  }

  /* 禁用状态下的复选框样式 */
  .el-checkbox__input.is-disabled .el-checkbox__inner {
    border-color: #fff;
    /* 边框颜色 */
    height: 18px;
    cursor: pointer;
    display: block !important;
    float: right;
    /* 调整锁图标大小 */
    background-position: center;
    /* 图标居中 */
    background: url('@/assets/images/suo.png') no-repeat;
    /* 鼠标悬停显示小手 */
    background-size: 11px auto;
    padding-left: 10px;
    /* 背景色 */
  }
}

.filter-header {
  display: flex;
  font-weight: bold;
  height: 53px;
  line-height: 53px;
  border-bottom: 1px solid #C7C7C7;
}

.filter-item {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #C7C7C7;
}

.filter-label {
  width: 120px;
  padding-left: 20px;
  font-size: 16px;
  font-weight: bold;

}

.filter-content {
  padding: 10px 20px;
  flex: 1;
  min-height: 45px;
  gap: 0 10px !important;
  /* 确保容器有最小高度，避免内容过短时变形 */
  align-content: flex-start;
  /* 默认垂直对齐方式 */
}

.button-container {
  display: flex;
  justify-content: center;
  /* 让按钮并排居中 */
  gap: 10px;
  /* 按钮之间的间距 */
  margin-top: 20px;
}

.el-table {
  margin-top: 20px;
}

/* 自定义按钮样式 */
.custom-search-btn {
  width: 106px;
  height: 35px;
  border-radius: 3px;
  background: #FF9833;
  font-size: 16px;
  color: #fff !important;
  /* 设置文字颜色为 #fff */
  text-align: center;

  /* 移除 Element Plus 默认的 primary 样式 */
  &.el-button--primary {
    background-color: #FF9833;
    border-color: #FF9833;

    &:hover,
    &:focus {
      background: lighten(#FF9833, 10%);
      border-color: lighten(#FF9833, 10%);
    }
  }
}
</style>
